<?php
declare (strict_types = 1);

namespace app\index\controller;
use app\common\model\NewsModel;
use app\common\model\CasesModel;
use app\common\model\InviteModel;
use app\common\model\SettingModel;
use app\common\model\MessagesModel;
use app\common\model\DingdingModel;     //钉钉消息通知
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use useragent\useragent;                //获取客户端系统、浏览器信息
use PHPMailer\PHPMailer\PHPMailer;      //评论邮件通知
use PHPMailer\PHPMailer\SMTP;           //评论邮件通知
use PHPMailer\PHPMailer\Exception;      //评论邮件通知


class Messages extends Common
{
    
    public function e_mail($nickname,$content){
        $config = SettingModel::where('group','zh')->column('value','name');
        $toemail = $config['email'];//定义收件人的邮箱
        $mail = new PHPMailer();
        $mail->isSMTP();// 使用SMTP服务
        $mail->CharSet = $config['CharSet'];// 编码格式为utf8
        $mail->Host = $config['Host'];// 发送方的SMTP服务器地址
        $mail->SMTPAuth = true;// 是否使用身份验证
        $mail->Username = $config['Username'];// 发送方的邮箱用户名，
        $mail->Password = $config['Password'];//发送方客户端的16位授权密码,而不是邮箱的登录密码！
        $mail->SMTPSecure = $config['SMTPSecure'];// 使用ssl协议方式
        $mail->Port = $config['Port'];// 163邮箱的ssl协议方式端口号是465/994 qq邮箱的是465/587
        $mail->setFrom($config['Username'],"{$config['system_name']} - 系统邮箱");// 设置发件人信息，如邮件格式说明中的发件人，
        $mail->addAddress($toemail,$config['system_name']);// 设置收件人信息，如邮件格式说明中的收件人，
        $mail->addReplyTo($config['email'],"站长邮箱");//收件人收到邮件后，如果要回复，回复邮件将要发送到的邮箱地址
        $mail->isHTML(true);//支持Html代码
        $mail->Subject = $nickname." 在您的网站留言了！";// 邮件标题
        $mail->Body = '<style>#p-mail-notify{font-size:14px;border:1px solid #dddddd;border-radius:10px;font-family:-apple-system,BlinkMacSystemFont,Roboto,Oxygen,Ubuntu,Cantarell,sans-serif;}#p-mail-notify a{display:inline-block;text-decoration:none;transition:all .3s;}#p-mail-notify a:hover{padding:0 5px;}#p-mail-notify .header,#p-mail-notify .footer{background-color:#007bff;padding:15px;color:#fff;}#p-mail-notify .header{border-top-left-radius:10px;border-top-right-radius:10px;}#p-mail-notify .header a{color:#ffcc33;}#p-mail-notify .main .tips a{color:#007bff;}#p-mail-notify .footer{font-size:12px;background-color:#8f969c;border-bottom-left-radius:10px;border-bottom-right-radius:10px;}#p-mail-notify .main{padding:15px;}#p-mail-notify .main .content-item{padding:10px;background-color:#343a40;border-radius:5px;color:#fff;margin:10px 0;}#p-mail-notify .main .tips{font-size:12px;color:#343a40;}</style>
            <div id="p-mail-notify">
                <div class="header">
                    站长：您好，有人在您的网站留言了!：
                </div>
                <div class="main">
                    留言昵称：
                    <div class="content-item me">'.$nickname.'</div>
                    留言内容为：
                    <div class="content-item">'.$content.'</div>
                    留言时间：'.date("Y-m-d H:i:s",time()).'<br />
                    留言状态：待审核<br />
                </div>
                <div class="footer">
                    <span>本邮件为 '.$config['system_name'].' 自动发送，请勿直接回复<br />版权所有 盗版必究 本站任何文章转载均需要文章地址+评论</span>
                </div>
            </div>';// 邮件正文内容
        if(!$mail->send()){// 发送邮件
            return json(['code'=>0, 'msg'=>$mail->ErrorInfo]);
        }
    }
    
    public function add(){
        $pid        = input('pid');
        $nickname   = input('nickname');
        $content    = input('comment');
        $mail       = input('mail');
        $url_s      = input('comurl');
        $pcode      = input('pcode');
        $phone_s    = input('nickqq');
        $messip     = get_client_ip();
        $nowTime    = time();
        $auth = new DingdingModel();
        
        $config = SettingModel::where('group',$this->lang)->column('value','name');
        $MessAdmin = $config['system_message'];
        $Messmail_ss = $config['system_mail_hh'];     //查询邮件通知功能是否关闭
        //查询站内是否已关闭评论功能
        if($MessAdmin == 'off'){
            return json(['code'=>1001, 'msg'=>'评论功能已关闭!']);
        }
        $IPInvite = InviteModel::where('ip_list',$messip)->where('status',1)->find();
        // 查询评论IP是否存在黑名单
        if($messip == $IPInvite['ip_list']){
            return json(['code'=>1002, 'msg'=>'评论或留言提交失败，因为IP已进入黑名单!']);
        }
        //获取用户系统、浏览器版本信息
        $agent = $_SERVER['HTTP_USER_AGENT'];
        $useragent = UserAgent_C::analyze($agent);
        //将该信息拆分存储
        $ptitle = $useragent->platform['title'];
        $pimage = $useragent->platform['image'];
        $btitle = $useragent->browser['title'];
        $bimage = $useragent->browser['image'];
        //存储该信息 前端转换
        $agentAll = '[faimg]../static/'.$pimage.'[/faimg]&nbsp;'.$ptitle.'&nbsp;&nbsp;[faimg]../static/'.$bimage.'[/faimg]'.$btitle;
        
        //将留言去除特殊符号 仅保留中文、字母、数字、下划线
        $encoding='utf8';
        $pattern = ($encoding=='utf8')?'/[\x{4e00}-\x{9fa5}a-zA-Z0-9_]/u':'/[\x80-\xFF]/';
        preg_match_all($pattern,$content,$result);
        $temp = join('',$result[0]);
        //获取违规关键词
        $filePath = dirname(dirname(dirname(dirname(__file__)))).'/WordKey.txt';
        $words = file($filePath);
        foreach ($words as $word) {
            $word = str_replace(array("\r\n", "\r", "\n", "/", "<", ">", "=", " "), '', $word);
        }  
        // /u: 表示按照unicode，UTF-8的规则匹配，如汉字的匹配
        // /i：表示匹配时不区分大小写，如URL的匹配
        // /s: 表示把字符串视作单行
        if(!$content){
            return json(['code'=>1003, 'msg'=>'评论或留言未填写！']);
        }
        if(preg_match("/$word/i",$temp)){
            return json(['code'=>1004, 'msg'=>'评论或留言中存在违规词语！']);
        }    // 验证QQ号是否为空 不为空则正则判断QQ号是否正确
        if(!$phone_s){
            $phone_s = null;
        }else{  
    		if(!preg_match('/^[1-9]([0-9]{4,10})$/u',$phone_s)) {
    			return json(['code'=>1005, 'msg'=>'QQ号码错误!']);
    		}
        }
        if(!$nickname){
            return json(['code'=>1006, 'msg'=>'昵称未填写']);
        }
        if(preg_match("/$word/i",$nickname)){
            return json(['code'=>1007, 'msg'=>'昵称中存在违规词语！']);
        }
        if(!$mail){
            return json(['code'=>1008, 'msg'=>'电子邮件未填写']);
        } 
        // /^[0-9a-zA-Z]+@(([0-9a-zA-Z]+)[.])+[a-z]{2,4}$/i
        if(!preg_match("/^([a-zA-Z0-9]+[_|\_|\.]?)*[0-9a-zA-Z]+@(([0-9a-zA-Z]+)[.])+[a-z]{2,4}$/i",$mail )){ // 先验证邮箱
            return json(['code'=>1009, 'msg'=>'电子邮件地址格式错误！']);
        }
        //验证评论手机或者QQ号是否为空及是否存在
        if(!$phone_s){
            $avata = MessagesModel::where(['messip'=>$messip,'nickname'=>$nickname])->order('id', 'asc')->value('avatar');
            if(!empty($avata)){
                $avatar = $avata;
            }else{
                $avatar = '/storage/avatar/message/'.rand(1,198).'.jpg';
            }
        }else{
            $avatar = 'https://q1.qlogo.cn/g?b=qq&nk='.$phone_s.'&s=40';
        }
        //获取用户IP地址并转换为真实物理地址
        $con = file_get_contents('https://apis.map.qq.com/ws/location/v1/ip?key=xxxxxx&ip='.$messip);
        $json = json_decode($con,true);
        if($json['status'] == 0){
            $ipdz = $json['result']['ad_info']['nation'].$json['result']['ad_info']['province'].$json['result']['ad_info']['city'].$json['result']['ad_info']['district'];
        } else {
            $ipdz = "未获取到地址,你可能住在火星";
        }
        $StTitle = '';
        if($pid == '0'){
            $StTitle = '吐槽留言';
        }else if($pid <> '0'){
            $StTitle = NewsModel::where('id',$pid)->value( 'title' );
        }
        //查询同用户、同目录下最新评论、留言时间
        $ctime = MessagesModel::where(['messip'=>$messip,'pid'=>$pid])->order('id', 'desc')->value('create_time');
        if(!empty($ctime)){
            if($ctime + $config['message_reply'] > $nowTime){
                return json(['code'=>1010, 'msg'=>'留言过于频繁，请在1小时后再次尝试！']);
            }else{
                MessagesModel::create([
                    'pid'       => $pid,
                    'nickname'  => $nickname,
                    'content'   => $content,
                    'mail'      => $mail,
                    'pcode'     => $pcode,
                    'url_s'     => $url_s,
                    'phone_s'   => $phone_s,
                    'messip'    => $messip,
                    'avatar'    => $avatar,
                    'ipmess'    => $ipdz,
                    'useragent' => $agentAll,
                ]);
                if($Messmail_ss == 'on'){
                    $this->e_mail($nickname,$content);
                }
                $Dingmsg = '网友《'.$nickname.'》在《'.$StTitle.'》留言了，留言内容：'.$content.'，留言IP：'.$messip.'';
                $str = $auth->dingding_up($Dingmsg);
                return json(['code'=>0, 'msg'=>'评论或留言 提交成功！']);
            }
        }else{
            MessagesModel::create([
                'pid'       => $pid,
                'nickname'  => $nickname,
                'content'   => $content,
                'mail'      => $mail,
                'pcode'     => $pcode,
                'url_s'     => $url_s,
                'phone_s'   => $phone_s,
                'messip'    => $messip,
                'avatar'    => $avatar,
                'ipmess'    => $ipdz,
                'useragent' => $agentAll,
            ]);
            if($Messmail_ss == 'on'){
                $this->e_mail($nickname,$content);
            }
            $Dingmsg = '网友《'.$nickname.'》在《'.$StTitle.'》留言了，留言内容：'.$content.'，留言IP：'.$messip.'';
            $str = $auth->dingding_up($Dingmsg);
            return json(['code'=>0, 'msg'=>'评论或留言 提交成功！']);
        }
    }

}
